//
//  HomeStatusCell.swift
//  WeiBo
//
//  Created by 江潘 on 15/7/1.
//  Copyright © 2015年 江潘. All rights reserved.
//

import UIKit
import SDWebImage

let JPReuserID = "JPReuserID"

class HomeStatusCell: UITableViewCell,UICollectionViewDataSource {
    
    var heightContraint:NSLayoutConstraint?
    var widthContraint:NSLayoutConstraint?
    
    var status:Status? {
        didSet{
            
            let size = caculatePicViewSize(status!)
            
            heightContraint?.constant = size.height
            widthContraint?.constant = size.width
            
            pictureView.reloadData()
            
            iconView.sd_setImageWithURL(NSURL(string: (status?.user?.profile_image_url)!))
            
            nameLabel.text = status?.user?.screen_name
            nameLabel.font = UIFont.systemFontOfSize(14)
            
            timelabel.text = status?.created_at
            timelabel.font = UIFont.systemFontOfSize(8)
            timelabel.textColor = UIColor.orangeColor()
            

            VerifiedView.image = UIImage(named:(status?.user?.verified_icon)!)
            
            if status?.source != "" {
                
                let components = status?.source?.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString:"<>"))
                
                let source = components![2]
                
                sourceLable.text = "来自 \(source)"

            }
            
            sourceLable.font = UIFont.systemFontOfSize(8)
            
            sourceLable.textColor = UIColor.grayColor()
            
            vipView.image = UIImage(named: (status?.user?.mbrank_img)!)
            
            contentLable.text = status?.text
            
            contentLable.font = UIFont.systemFontOfSize(13)
            
        }
    }
    
    func rowHeight(status:Status) -> CGFloat{
    
        self.status = status
        
        layoutIfNeeded()
        
        return CGRectGetMaxY(footerView.frame)
    }
    
    private func caculatePicViewSize(caculatestatus:Status) -> CGSize{
    
        let count = caculatestatus.imgURLS?.count ?? 0
        
        if count == 0{
            
            return CGSizeZero
        }
        if count == 1{
            
            let key = caculatestatus.imgURLS![0].absoluteString
            
            let cacheImg = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            flowLayout.itemSize = cacheImg.size
            
            return flowLayout.itemSize
        }
        
        let itemSize = CGSizeMake(90, 90)
        let margin:CGFloat = 10.0
        flowLayout.minimumInteritemSpacing = margin
        flowLayout.minimumLineSpacing = margin
        flowLayout.itemSize = itemSize
        
        if count == 4{
            
            return CGSizeMake(itemSize.width * 2 + margin, itemSize.height * 2 + margin)
        }
        
        let rowCount = 3
        
        let h = (CGFloat((count - 1) / rowCount) + 1) * itemSize.height + margin * CGFloat((count - 1) / rowCount)
        
        return CGSizeMake(290, h)
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        setupCell()
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupCell(){
        
        let screenWidth = UIScreen.mainScreen().bounds.width
        let topView = UIView()
        topView.backgroundColor = UIColor.lightGrayColor()
        addSubview(topView)
        topView.ff_AlignInner(ff_AlignType.TopCenter, referView: self, size: CGSize(width: screenWidth, height: 10), offset: CGPointZero)
        addSubview(iconView)
        addSubview(nameLabel)
        addSubview(vipView)
        addSubview(timelabel)
        addSubview(sourceLable)
        addSubview(VerifiedView)
        addSubview(contentLable)
        addSubview(pictureView)
        addSubview(footerView)
        
        iconView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSizeMake(34, 34), offset: CGPointMake(12, 12))
        
        nameLabel.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPointMake(12, 0))
        
        vipView.ff_AlignHorizontal(ff_AlignType.TopRight, referView: nameLabel, size: CGSizeMake(12, 12), offset: CGPointMake(8, 2))
        
        timelabel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: nameLabel, size: nil, offset: CGPointMake(0, 3))
        
        sourceLable.ff_AlignHorizontal(ff_AlignType.TopRight, referView: timelabel, size: nil, offset: CGPointMake(12, 0))
        
        
        VerifiedView.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconView, size: CGSizeMake(14, 14), offset: CGPointMake(-7, 7))
    
        contentLable.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconView, size: nil, offset: CGPointMake(0, 8))
        
        let picCons = pictureView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: contentLable, size: CGSizeMake(290, 90), offset: CGPointMake(0, 16))
        
        widthContraint = pictureView.ff_Constraint(picCons, attribute: NSLayoutAttribute.Width)
        
        heightContraint = pictureView.ff_Constraint(picCons, attribute: NSLayoutAttribute.Height)
        
        footerView.ff_AlignInner(ff_AlignType.BottomLeft, referView: pictureView, size: CGSizeMake(UIScreen.mainScreen().bounds.width, 36), offset: CGPointMake(-12, 46))
    }
    
    // 懒加载
    
    lazy var iconView:UIImageView = {
        let imgV = UIImageView()
        return imgV
    }()
    
    lazy var vipView:UIImageView = {
        let imgV = UIImageView()
        return imgV
    }()
    
    lazy var nameLabel:UILabel = {
        let lb = UILabel()
        return lb
    }()
    
    lazy var VerifiedView:UIImageView = {
        let imgV = UIImageView()
        return imgV
    }()
    
    lazy var timelabel:UILabel = {
        let lb = UILabel()
        return lb
    }()
    
    lazy var sourceLable:UILabel = {
        let lb = UILabel()
        return lb
    }()
    
    lazy var contentLable:UILabel = {
        let lb = UILabel()
        lb.numberOfLines = 0
        lb.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 12
        return lb
    }()
    
    lazy var footerView: StatusFooterView = StatusFooterView()
    
    lazy var pictureView:UICollectionView = {
    
        let picView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout:self.flowLayout)
        
        picView.registerClass(pictureCell.self, forCellWithReuseIdentifier:JPReuserID )
        
        picView.dataSource = self
        
        picView.backgroundColor = UIColor.whiteColor()
        
        return picView
    }()
    // UICollectionView的布局方法
    lazy var flowLayout:UICollectionViewFlowLayout = {
    
        let layout = UICollectionViewFlowLayout()
        
        layout.minimumLineSpacing = 8.0
        
        layout.minimumInteritemSpacing = 8.0
        
        layout.itemSize = CGSizeMake(40,40)
        
        return layout
    }()
    
    // UICollectionView 数据源方法
   
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        
        return status?.imgURLS?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(JPReuserID, forIndexPath: indexPath) as! pictureCell
        
        cell.imgURL = status!.imgURLS![indexPath.item]
        
        return cell
    }
    
   func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int{
    
        return 1
    }
}

class pictureCell: UICollectionViewCell {
    
    var picView:UIImageView = UIImageView()
    
    var imgURL:NSURL?{
    
        didSet{
            
            picView.sd_setImageWithURL(imgURL!)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 设置图片填充模式
        picView.contentMode = UIViewContentMode.ScaleAspectFill
        
        picView.clipsToBounds = true
        
        addSubview(picView)
        picView.ff_Fill(self)
    
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class StatusFooterView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        
        addSubview(forwardButton)
        addSubview(commontButton)
        addSubview(likeButton)
        
        ff_HorizontalTile([forwardButton, commontButton, likeButton], insets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///  转发按钮
    lazy var forwardButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("转发", forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "timeline_icon_retweet"), forState: UIControlState.Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        btn.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
        
        return btn
    }()
    ///  评论按钮
    lazy var commontButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("评论", forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "timeline_icon_comment"), forState: UIControlState.Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        btn.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
        
        return btn
        }()
    ///  点赞按钮
    lazy var likeButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("赞", forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "timeline_icon_unlike"), forState: UIControlState.Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        btn.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
        return btn
        
        }()
}


